<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\LibApi\CqstLibController;
use App\Models\AccessNum;
use App\Models\Activity;
use App\Models\ActivityApply;
use App\Models\AnswerActivity;
use App\Models\AnswerActivityProblem;
use App\Models\AnswerActivityUnitUserNumber;
use App\Models\AppInviteCode;
use App\Models\AppInviteCodeBehavior;
use App\Models\AppViewGray;
use App\Models\Banner;
use App\Models\BookHomeOrder;
use App\Models\BookHomePurchase;
use App\Models\BookRecom;
use App\Models\BookTypes;
use App\Models\CodeBorrowLog;
use App\Models\CodeReturnLog;
use App\Models\ContestActivity;
use App\Models\Digital;
use App\Models\Goods;
use App\Models\NewBookRecommend;
use App\Models\News;
use App\Models\OtherAccessNum;
use App\Models\PictureLive;
use App\Models\RecommendUser;
use App\Models\Reservation;
use App\Models\ReservationApply;
use App\Models\ScenicWorks;
use App\Models\SystemInfo;
use App\Models\TurnActivity;
use App\Models\UserInfo;
use App\Models\UserLibraryInfo;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 微信首页
 */
class IndexController extends CommonController
{


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 第一次验证邀请码是否正确  （空方法，可不要任何代码，因为在中间件已经验证）
     * invite_code
     */
    public function checkInviteCode()
    {
        // $invite_code = $this->request->invite_code;

        // if (empty($invite_code) || strlen($invite_code) != 6 || !is_numeric($invite_code)) {
        //     return  response()->json(['code' => 302, 'msg' => '邀请码输入错误']);
        // }

        // //验证token有效期
        // $appInviteCodeModel = new AppInviteCode();
        // $invite_code_id = $appInviteCodeModel->checkInviteCode($invite_code);
        // if (is_string($invite_code_id)) {
        //     return  response()->json(['code' => 302, 'msg' => $invite_code_id]);
        // }
        return $this->returnApi(200, '获取成功', true);
    }




    /**
     * 官网首页
     * token 可有可无
     */
    public function index()
    {
        $user_id = $this->request->user_info['id'];

        //获取缓存数据
        $cache_key = md5($user_id . '_index_data');
        $data = Cache::get($cache_key);
        if (empty($data)) {
            if (!empty($user_id)) {
                $user_info = UserInfo::with(
                    [
                        'conWechat' => function ($query) {
                            $query->select('id', 'nickname', 'head_img', 'tel');
                        },
                        'conLibrary' => function ($query) {
                            $query->select('id', 'username', 'account', 'end_time');
                        }
                    ]
                )
                    ->select('id', 'wechat_id', 'account_id', 'qr_url')
                    ->where('id', $user_id)
                    ->first()
                    ->toArray();

                $system_info_number = SystemInfo::where('is_look', 2)->where('user_id', $user_id)->count();
            } else {
                $user_info = null;
                $system_info_number = 0;
            }
            $data['user_info'] = $user_info;
            $data['system_info_number'] = $system_info_number;

            //banner图片
            $banner = Banner::getBannerList(1);
            if (empty($banner)) {
                $banner[0]['img'] = 'default/default_banner.png';
                $banner[0]['link'] = '';
                $banner[0]['name'] = '默认图片';
            }
            $data['banner'] = $banner;
            //获取新闻信息
            $newsModel = new News();
            $news = $newsModel->lists(null, null, null, null, 3); //热门新闻,置顶新闻
            $data['news'] = $news['data']; //热门新闻,置顶新闻
            foreach ($data['news'] as $key => $val) {
                $data['news'][$key]['img'] = $val['img'] ? explode('|', $val['img']) : null;
            }
            $data['news'] = $this->disDataSameLevel($data['news'], 'con_type', ['type_name' => 'type_name']);
            // //好书推荐
            $newBookRecommendModel = new NewBookRecommend();
            $data['new_book_recom'] = $newBookRecommendModel->recomLists(null, 1);
            $data['new_book_recom'] = $this->disDataSameLevel($data['new_book_recom'], 'con_type', ['type_name' => 'type_name']);
            // //活动
            $activityModel = new Activity();
            $data['activity'] = $activityModel->getActRecomList(3);
            //获取商品信息
            $goodsModel = new Goods();
            $user_id = !empty($this->request->user_info['id']) ? $this->request->user_info['id'] : null;
            $goods = $goodsModel->lists(null, $user_id, null, 5);
            if ($goods) {
                $data['goods'] = $goods['data'];
            } else {
                $data['goods'] = null;
            }
            //预约
            $reservationModel = new Reservation();
            $reservation = $reservationModel->lists(['id', 'node', 'name', 'img', 'apply_number', 'intro'], 0, null, null, null, 1, 2);
            $data['reservation'] = $reservation['data'];

            // //数字资源
            $digitalModel = new Digital();
            $digital = $digitalModel->lists(null, null, null, 1, null, null, 'sort desc', 9);
            $data['digital'] = $digital['data'];


            //预约，是否显示座位预约和到馆预约按钮
            // $data['make']['arrive_make'] = true; //true 为显示，false或空或不存在则不显示
            // $data['make']['seat_make'] = true;

            //阅读互动
            $data['read_interactive'] = $this->readInteractive();

            $appViewGrayModel = new AppViewGray();
            $data['color']['is_gray'] = $appViewGrayModel->isViewGray(); //是否显示灰色

            /** 是否显示阅读账单 */
            if (in_array(date('m'), config('other.year_bill_open_month'))) {
                $data['year_bill'] = date('Y') . '年度账单'; //前端样式滚动显示
            } else {
                $data['year_bill'] = '';
            }

            Cache::put($cache_key, $data, 60); //缓存一分钟
        }

        //添加访问量
        $accessNumObj = new AccessNum();
        $accessNumObj->add(1);

        //增加行为分析
        $appInviteCodeBehaviorModel = new AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(30);

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 阅读互动
     */
    public function _readInteractive()
    {
        //获取答题
        $answerActivityModel = new AnswerActivity();
        $answer_activity = $answerActivityModel->select('id', DB::raw('1 as type'), 'title', 'img', 'start_time', 'end_time', 'answer_start_time', 'answer_end_time')->where('is_del', 1)->where('is_play', 1)->orderByDesc('end_time')->limit(1)->get()->toArray();
        //获取活动状态  活动状态 1 活动未开始 2.答题未开始 3.进行中 4.答题已结束  5 活动已结束
        if ($answer_activity) {
            $answer_activity[0]['status'] = $answerActivityModel->getActListStatus($answer_activity[0]);
        } else {
            $answer_activity = [];
        }

        //获取在线抽奖
        $turnActivityModel = new TurnActivity();
        $turn_activity = $turnActivityModel->select('id', DB::raw('2 as type'), 'title', 'img', 'start_time', 'end_time', 'turn_start_time', 'turn_end_time')->where('is_del', 1)->where('is_play', 1)->orderByDesc('end_time')->limit(1)->get()->toArray();
        //获取活动状态   活动状态 1 活动未开始 2.抽奖未开始 3.进行中 4.抽奖已结束  5 活动已结束
        if ($turn_activity) {
            $turn_activity[0]['status'] = $turnActivityModel->getActListStatus($turn_activity[0]);
        } else {
            $turn_activity = [];
        }

        //获取大赛
        $contestActivityModel = new ContestActivity();
        $contest_activity = $contestActivityModel->select('id', DB::raw('3 as type'), 'title', 'app_img as img', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('is_del', 1)->where('is_play', 1)->orderByDesc('con_end_time')->limit(1)->get()->toArray();
        //获取活动状态   活动状态 1.大赛未开始  2 投稿中  3 投票未开始  4 投票中  5 投票已结束  6 大赛已结束
        if ($contest_activity) {
            $contest_activity[0]['status'] = $contestActivityModel->getContestStatus($contest_activity[0]);
        } else {
            $contest_activity = [];
        }

        //图片直播
        $pictureLiveModel = new PictureLive();
        $picture_activity = $pictureLiveModel->select('id', DB::raw('4 as type'), 'title', 'img', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('is_del', 1)->where('is_play', 1)->orderByDesc('con_end_time')->limit(1)->get()->toArray();
        //获取活动状态   活动状态 1.活动未开始  2 投稿中  3 投票未开始  4 投票中  5 投票已结束  6 活动已结束
        if ($picture_activity) {
            $picture_activity[0]['status'] = $pictureLiveModel->getPictureLiveStatus($picture_activity[0]);
        } else {
            $picture_activity = [];
        }

        return array_merge($answer_activity, $turn_activity, $contest_activity, $picture_activity);
    }

    /**
     * 阅读互动
     */
    public function readInteractive()
    {
        //图片直播
        $pictureLiveModel = new PictureLive();
        //$picture_activity = $pictureLiveModel->select('id', DB::raw('4 as type'), 'title', 'img', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('is_del', 1)->where('is_play', 1)->whereBetween('con_start_time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])->orderBy('id')->get()->toArray();
        $picture_activity = $pictureLiveModel->select('id', DB::raw('4 as type'), 'title', 'img', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('is_del', 1)->where('is_play', 1)->where('con_end_time', '>', date('Y-m-d 00:00:00'))->orderBy('con_end_time')->limit(1)->get()->toArray();
        if (empty($picture_activity)) {
            $picture_activity = $pictureLiveModel->select('id', DB::raw('4 as type'), 'title', 'img', 'con_start_time', 'con_end_time', 'vote_start_time', 'vote_end_time')->where('is_del', 1)->where('is_play', 1)->orderByDesc('con_end_time')->limit(1)->get()->toArray();
        }
        //获取活动状态   活动状态 1.活动未开始  2 投稿中  3 投票未开始  4 投票中  5 投票已结束  6 活动已结束
        if ($picture_activity) {
            $picture_activity[0]['status'] = $pictureLiveModel->getPictureLiveStatus($picture_activity[0]);
        } else {
            $picture_activity = [];
        }

        return  $picture_activity;
    }


    /**
     * 获取年度账单
     * @param token 用户token
     */
    public function getYearBill()
    {
        $user_guid = $this->request->token;
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];

        //123月份，显示去年数据，其余显示今年数据
        if (in_array(date('m'), [1, 2, 3])) {
            $start_time = date('Y-01-01', strtotime('-1 year'));
            $end_time = date('Y-12-31', strtotime('-1 year'));
            $year = date('Y', strtotime('-1 year'));
        } else {
            $start_time = date('Y-01-01');
            $end_time = date('Y-12-31');
            $year = date('Y');
        }

        //相识时间
        $data['meet_data'] = [
            'year' => date('Y', strtotime($this->request->user_info['create_time'])),
            'month' => date('m', strtotime($this->request->user_info['create_time'])),
            'day' => date('d', strtotime($this->request->user_info['create_time'])),
            'meet_day' => time_diff_day(strtotime($this->request->user_info['create_time']), time()),
        ];

        //荐购天数
        $recommendUserModel = new RecommendUser();
        $data['recommend']['recommend_number'] = $recommendUserModel->where('user_id', $user_id)->whereBetween('create_time', [$start_time, $end_time])->count();

        //活动报名
        $activityModel = new Activity();
        $activityApplyModel = new ActivityApply();
        //获取举办数量
        $data['activity']['activity_number'] = $activityModel->whereBetween('create_time', [$start_time, $end_time])->where('is_del', 1)->count();
        //参加活动数量
        $data['activity']['self_activity_number'] = $activityApplyModel->where('user_id', $user_id)->whereBetween('create_time', [$start_time, $end_time])
            ->whereIn('status', [1, 4])->count();

        //手机扫码借
        $codeBorrowLogModel = new CodeBorrowLog();
        $codeReturnLog = new CodeReturnLog();
        list($data['code_borrow']['code_borrow_number'], $data['code_borrow']['code_borrow_type']) = $codeBorrowLogModel->userBorrowData($user_id, $start_time, $end_time);
        $data['code_borrow']['code_return_number'] = $codeReturnLog->where('user_id', $user_id)->whereBetween('create_time', [$start_time, $end_time])->count();


        //预约报名
        $reservationApplyModel = new ReservationApply();
        //参数预约数量
        $data['reservation']['reservation_curator'] = $reservationApplyModel->makeReservationData($user_id, 5, null, null, $start_time, $end_time); //到馆
        $data['reservation']['reservation_seat'] = $reservationApplyModel->makeReservationData($user_id, 6, null, null, $start_time, $end_time); //座位
        $data['reservation']['reservation_number'] = $data['reservation']['reservation_curator'] + $data['reservation']['reservation_seat'];
        //文旅打卡次数
        $scenicWorksModel = new ScenicWorks();
        $data['scenic']['scenic_works_number'] = $scenicWorksModel->where('user_id', $user_id)->whereBetween('create_time', [$start_time, $end_time])->where('status', [1, 3])->count();

        //答题活动
        $answerActivityModel = new AnswerActivity();
        $answerActivityUnitUserNumberModel = new AnswerActivityUnitUserNumber();
        $answerActivityProblemModel = new AnswerActivityProblem();
        //获取举办数量
        $data['answer_activity']['answer_activity_number'] = $answerActivityModel->whereBetween('create_time', [$start_time, $end_time])->where('is_del', 1)->count();
        //参加活动数量
        $data['answer_activity']['self_answer_activity_number'] = $answerActivityUnitUserNumberModel->where('user_guid', $user_guid)->whereBetween('create_time', [$start_time, $end_time])->count('act_id');
        //答题正确数
        $data['answer_activity']['self_answer_problem_success_number'] = $answerActivityProblemModel->userAnswerSuccessNumber($user_guid, $start_time, $end_time);

        //图书到家
        $bookHomeOrderModel = new BookHomeOrder();
        $data['book_home']['book_home_total_order_number'] = $bookHomeOrderModel->getOrderNumber(null, [2, 6, 7, 8, 9], null, null, $user_id, $start_time, $end_time); //图书到家使用总次数
        $data['book_home']['book_home_lib_orde_number'] = $bookHomeOrderModel->getOrderNumber(2, [2, 6, 7, 8, 9], null, null, $user_id, $start_time, $end_time); //图书到家馆藏书使用总次数
        $data['book_home']['book_home_new_orde_number'] = $bookHomeOrderModel->getOrderNumber(1, [2, 6, 7, 8, 9], null, null, $user_id, $start_time, $end_time); //图书到家新书使用总次数
        $bookHomePurchaseModel = new BookHomePurchase();
        $data['book_home']['book_home_total_book_number'] = $bookHomePurchaseModel->getBorrowData(null, $user_id, $start_time, $end_time); //图书到家使用总次数
        $data['book_home']['book_home_lib_book_number'] = $bookHomePurchaseModel->getBorrowData(2, $user_id, $start_time, $end_time); //图书到家馆藏书使用总次数
        $data['book_home']['book_home_new_book_number'] = $bookHomePurchaseModel->getBorrowData(1, $user_id, $start_time, $end_time); //图书到家新书使用总次数

        return $this->returnApi(200, '获取成功', true, $data);
    }


    /**
     * 记录其他数据访问量
     * @param type 1 数字阅读  2 图书到家
     */
    public function otherAccressAdd()
    {
        $type = $this->request->input('type');
        if (empty($type)) {
            return $this->returnApi(201, '参数错误');
        }
        $otherAccessNumModel = new OtherAccessNum();
        $res = $otherAccessNumModel->add($type);
        if ($res) {
            return $this->returnApi(200, '添加成功', true);
        }
        return $this->returnApi(202, '添加失败');
    }


    /**
     * 根据地址转经纬度、或根据经纬度转换地址
     * @param lon  经度   经纬度 必须同时存在
     * @param lat  纬度
     * @param province 省
     * @param city 市
     * @param district 区、县
     * @param address 补充地址
     */
    public function getAddressOrLonLat()
    {
        $lon = $this->request->lon;
        $lat = $this->request->lat;
        $province = $this->request->province;
        $city = $this->request->city;
        $district = $this->request->district;
        $address = $this->request->address;

        if ((empty($lon) || empty($lat)) && (empty($city))) {
            return $this->returnApi(201, '参数错误');
        }

        if (!empty($lon) && !empty($lat)) {
            //根据经纬度获取地址
            $map = $this->getAddressByLonLat($lon, $lat);

            if (is_string($map)) return $this->returnApi(202, $map);
            $data['province']      = $map['province'];
            $data['city']          = !empty($map['city']) ? $map['city'] : $map['province'];
            $data['district']        = $map['district'];
            $data['address']       = $map['remark'];
        } else {
            $address = $province . $city . $district . $address;
            $map = $this->getLonLatByAddress($address);
            if (is_string($map)) return $this->returnApi(202, $map);
            $data['lon']                = $map['lon'];
            $data['lat']                = $map['lat'];
        }

        return $this->returnApi(200, '获取成功', true, $data);
    }
}
